package cn.edu.ldu.views.main;

import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.ChatHistoryEntity;
import cn.edu.ldu.entity.FriendsEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.*;
import com.alibaba.fastjson.JSON;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.*;

/**
 *
 * @author DYZ
 */
public class ChatUI extends javax.swing.JPanel {
    private FriendsEntity friend;
    private byte[] data = new byte[8096];
    /**
     * Creates new form Chat
     */
    public ChatUI(int width,int height,FriendsEntity friendsEntity) {
        friend = friendsEntity;
        initComponents(friend);
        this.setSize(width,height);
        this.setVisible(true);
    }

    //接受信息
    public void receiveMsg(ChatHistoryEntity Msg){
        txtMsg.append(Translate.stampToDate(Msg.getSendTime())+"\n"+labUsername.getText() +":"+Msg.getContent()+"\n");
    }

    public String getTalkerName(){
        return labUsername.getText();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents(FriendsEntity friend) {

        topPanel = new javax.swing.JPanel();
        labUsername = new javax.swing.JLabel();
        //btnSet = new javax.swing.JButton();
        txtPanel = new javax.swing.JPanel();
        btnBlod = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtSend = new javax.swing.JTextArea();
        btnCheckMsg = new javax.swing.JButton();
        btnSend = new javax.swing.JButton();
        msgPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtMsg = new javax.swing.JTextArea();

        setLayout(new java.awt.BorderLayout());

        topPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 0, 0)));

        labUsername.setText(friend.getUserAccountEntity().getNickName());


        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
                topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(topPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(labUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 320, Short.MAX_VALUE)
                                //.addComponent(btnSet)
                                .addContainerGap())
        );
        topPanelLayout.setVerticalGroup(
                topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(topPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(labUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        //.addComponent(btnSet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        )
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(topPanel, java.awt.BorderLayout.NORTH);

        btnBlod.setText("A");
        btnBlod.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnBlodMouseClicked(evt);
            }
        });

        txtSend.setColumns(20);
        txtSend.setRows(5);
        txtSend.setLineWrap(true);

        jScrollPane2.setViewportView(txtSend);

        btnCheckMsg.setText("查看聊天记录");
        btnCheckMsg.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCheckMsgMouseClicked(evt);
            }
        });

        btnSend.setText("发送");
        btnSend.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSendMouseClicked(evt);
            }
        });


        javax.swing.GroupLayout txtPanelLayout = new javax.swing.GroupLayout(txtPanel);
        txtPanel.setLayout(txtPanelLayout);
        txtPanelLayout.setHorizontalGroup(
                txtPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(txtPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(btnBlod)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnCheckMsg))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, txtPanelLayout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSend))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        txtPanelLayout.setVerticalGroup(
                txtPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(txtPanelLayout.createSequentialGroup()
                                .addGroup(txtPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnBlod)
                                        .addComponent(btnCheckMsg))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(txtPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnSend))
                                .addGap(0, 0, Short.MAX_VALUE))
        );

        add(txtPanel, java.awt.BorderLayout.SOUTH);

        msgPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("聊天界面"));

        txtMsg.setColumns(20);
        txtMsg.setRows(5);
        txtMsg.setEnabled(false);
        jScrollPane1.setViewportView(txtMsg);

        javax.swing.GroupLayout msgPanelLayout = new javax.swing.GroupLayout(msgPanel);
        msgPanel.setLayout(msgPanelLayout);
        msgPanelLayout.setHorizontalGroup(
                msgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
        );
        msgPanelLayout.setVerticalGroup(
                msgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
        );

        add(msgPanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>

    /**
     * 字体加粗
     */
    private void btnBlodMouseClicked(MouseEvent evt){
        if(evt.getClickCount() == 1)
        txtSend.setFont(new Font("宋体",Font.BOLD,15));
        else
        txtSend.setFont(new Font("宋体",0,15));
    }

    /**
     * 查询历史消息
     */
    private void btnCheckMsgMouseClicked(MouseEvent evt){
                InetAddress remoteAddr = null;
                try {
                    remoteAddr = InetAddress.getByName(Consts.ipv4);
                    //创建UDP套件字
                    DatagramSocket clientSocket = null;
                    clientSocket = new DatagramSocket();

                    //构造用户查看信息记录信息
                    Protocol protocol = new Protocol();
                    protocol.setKey("GetChatHistory");
                    protocol.setToken(UserController.getToken());

                    ChatHistoryEntity chatHistoryEntity = new ChatHistoryEntity();
                    chatHistoryEntity.setTalkerId(friend.getFriendId());
                    chatHistoryEntity.setSenderId(friend.getUserId());

                    //转字符
                    protocol.setData(JSON.toJSONString(chatHistoryEntity));
                    data = Translate.ObjectToByte(protocol);

                    //定义查看历史信息报文
                    DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
                    clientSocket.send(packet);


                    byte[] receiveData = new byte[8096];
                    packet = new DatagramPacket(receiveData, receiveData.length, remoteAddr, Consts.port);
                    clientSocket.receive(packet);
                    //查看发送结果
                    L.OK(packet, ChatUI.class);

                    Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());
                    pro.key();

                } catch (IOException e) {
                    e.printStackTrace();
                }
    }
    /**
     * 发送信息
     */
    private void btnSendMouseClicked(MouseEvent evt){
        try {
            DatagramSocket clientSocket = Ports.getCommon();
            Protocol protocol = new Protocol();
            protocol.setKey(Consts.P_CHAT_FRIEND);
            protocol.setToken(UserController.getToken());

            ChatHistoryEntity che = new ChatHistoryEntity();
            che.setSenderId(UserController.getUserEntity().getId());
            che.setTalkerId(friend.getFriendId());
            che.setMsg(1);
            che.setContent(txtSend.getText());
            che.setIsGroup(0);

            protocol.setData(JSON.toJSONString(che));

            byte[] data = Translate.ObjectToByte(protocol);
            DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(Consts.ipv4), Consts.port);
            clientSocket.send(packet);
            L.OK(packet, ChatUI.class);

            //在面板显示
            txtMsg.append(Util.nowDate()+"\n");
            txtMsg.append(UserController.getUserEntity().getUsername()+"："+txtSend.getText()+"\n");
            txtSend.setText("");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnBlod;
    private javax.swing.JButton btnCheckMsg;
    private javax.swing.JButton btnSend;
    //private javax.swing.JButton btnSet;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labUsername;
    private javax.swing.JPanel msgPanel;
    private javax.swing.JPanel topPanel;
    private javax.swing.JTextArea txtMsg;
    private javax.swing.JPanel txtPanel;
    private javax.swing.JTextArea txtSend;
    // End of variables declaration
}

